package se.hb.eme;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import se.hb.eme.api.Service;
import se.hb.eme.api.ServiceRequirement;
import se.hb.eme.api.helpers.ScheduleTypeEnum;
import se.hb.eme.api.helpers.ServiceTypeEnum;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/*
 *A Adapter-Activity for the different types of Api-calls to E-me.
 *For now just searchService is implemented, but we can collect all types of 
 *needed E-me Api-calls here
 * 
 * */

public class EmeApiAdapter {	
	private static final HttpContext localContext = new BasicHttpContext();	
	private static final HttpClient httpClient = new DefaultHttpClient();	
	
	private static final String eMeUrl = "http://192.168.105.55:80/eMe2_1_api";
	
	private EmeApiAdapter(){
		
	}

	/*@Override
	public void onCreate(Bundle arg) {
		super.onCreate(arg);
		arg = new Bundle();
		//here i should get which funtion to call and all
		//the parameters
		//returns for the moment just a populated string
		
		arg.putString("returnValues", searchServices());
		Intent intent = new Intent();
		intent.putExtras(arg);
		setResult(RESULT_OK);
		finish();
	}*/

	public static List<Service> searchServices() {		
		ArrayList<Service> services  = new ArrayList<Service>();
		
		try {
			//Make the request
			String callData = callEmeApi("/service/searchServices?serviceType=CONSUMERSERVICE");				
			JSONObject hashmap = new JSONObject(callData);
			JSONArray jServises  = hashmap.getJSONArray("services");
			GsonBuilder gsonb = new GsonBuilder(); 
			gsonb.registerTypeAdapter(ScheduleTypeEnum.class, new EnumJsonDeserializer(ScheduleTypeEnum.class));
			gsonb.registerTypeAdapter(ServiceTypeEnum.class, new EnumJsonDeserializer(ServiceTypeEnum.class));
			Gson gson = gsonb.create(); 
			//
			for (int i = 0; i < jServises.length(); i++) {
				services.add(gson.fromJson(jServises.getString(i), Service.class));	
			}			
			
		} catch (Exception e) {
			Log.e(e.toString(), e.getMessage());			
		}
		return services;
	}
	
	public static List<ServiceRequirement> getServiceRequirements(int serviceId){
		
		return null;
	}

	private static String callEmeApi(String params) throws ClientProtocolException, IOException{
		final HttpGet httpGet = new HttpGet(eMeUrl + params);
		HttpResponse response = httpClient.execute(httpGet, localContext);
		if (response.getStatusLine().getStatusCode() == 200){
			return readStringFromInputStream(response.getEntity().getContent());
		}
		else 
		{
			throw new IOException("Can't connect to eMe api, StatusCode: " + response.getStatusLine().getStatusCode() );
		}
		
	}
	
	private static String readStringFromInputStream(InputStream is) {
		BufferedReader in = new BufferedReader(new InputStreamReader(is));
		StringBuffer buffer = new StringBuffer();
		String line;
		try {
			while ((line = in.readLine()) != null) {
				buffer.append(line);
			}
		} catch (IOException e) {
			Log.e(e.toString(), e.getMessage());
			
		}
		return new String(buffer);
	}
	
}
